#!./bin/python
# ----------------------------------------------------------------------
# Cleanup hanging .pyc files
# ----------------------------------------------------------------------
# Copyright (C) 2007-2015 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------

# Python modules
import os
import sys
# NOC modules
from noc.settings import INSTALLED_APPS


class Cleanup(object):
    def __init__(self):
        self.errors = []
        self.changed = []

    def error(self, msg):
        self.errors += [str(msg)]

    def iter_files(self):
        """
        Yield all python files to be compiled
        """
        for app in INSTALLED_APPS:
            if not app.startswith("noc."):
                continue
            app = app[4:]
            for root, dirs, files in os.walk(app):
                for f in files:
                    if f.endswith(".pyc"):
                        yield os.path.join(root, f)

    def cleanup(self):
        for pyc in self.iter_files():
            py = pyc[:-1]
            if not os.path.exists(py):
                self.changed += [pyc]
                try:
                    os.unlink(pyc)
                except OSError as e:
                    self.error(e)

    def run(self):
        self.cleanup()
        if self.errors:
            print("ERROR")
            for e in self.errors:
                print(e)
            return 1
        elif self.changed:
            print("CHANGED")
            for c in self.changed:
                print("Removed %s" % c)
            return 0
        else:
            print("OK")
            return 0


if __name__ == "__main__":
    sys.exit(Cleanup().run())
